<?php

namespace XWAM\Addon\PXCallSystem\Model;

/**
 * 角色数据库模型
 *
 * @author SoChishun <14507247@qq.com>
 * @version 1.0
 * @since 1.0.0 <2015-3-25> SoChishun Added.
 */
class RoleModel extends AppbaseModel {

    protected $autoCheckFields = false;

    /**
     * 是否批量验证
     * @var boolean
     */
    protected $patchValidate = true;

    /**
     * 返回树形列表或刷新缓存
     * 
     * @param string $scope 命名范围
     * @since 1.0 <2015-3-25> SoChishun Added.
     */
    public function get_list($where = '', $field = 'id, title as text') {
        return $this->table(C('AUTH_CONFIG.AUTH_GROUP'))->where($where)->field($field)->select();
    }
    
    public function get_item($id){
        return $this->table(C('AUTH_CONFIG.AUTH_GROUP'))->find($id);
    }

    /**
     * 保存角色
     * @return true|string|array
     * @since 1.0 2015-3-6 by sutroon
     */
    public function save_role() {
        $rules = array(
            array('title', 'require', '角色必须填写!'),
            array('status', 'number', '状态有误!'),
        );
        if (!$this->validate($rules)->create()) {
            $this->returnMsg(false, $this->getError());
        }
        if ($this->data['id']) {
            $result = $this->save();
        } else {
            $result = $this->add();
        }
        return $this->returnMsg($result);
    }

    /**
     * 复制角色
     * @param int $id
     * @return array
     * @since 1.0 <2015-9-24> SoChishun Added.
     */
    public function copy_role($id = 0) {
        if (!$id) {
            return $this->returnMsg(false, '参数无效');
        }
        $role_table = C('AUTH_CONFIG.AUTH_GROUP');
        M()->execute("insert into $role_table (title,code,rules) select concat(title,'_new'),code,rules from $role_table where id=$id");
        $this->ajaxMsg(true);
    }

    /**
     * 删除角色
     * @param type $id
     * @return type
     * @since 1.0 <2015-3-6> SoChishun Added.
     * @since 2.0 <2015-9-24> SoChishun Refactoring.
     */
    public function delete_role($id = '') {
        if (!$id) {
            return $this->returnMsg(false, '参数无效');
        }
        $role_table = C('AUTH_CONFIG.AUTH_GROUP');
        // 判断是否有引用
        $user_role_ids = $this->table(C('AUTH_CONFIG.AUTH_GROUP_ACCESS'))->where(array('group_id' => array('in', $id)))->getField('group_id', true);
        if ($user_role_ids) {
            $names = $this->table($role_table)->where(array('id' => array('in', $user_role_ids)))->getField('name', true);
            return $this->returnMsg(false, '以下项目正在被用户使用,无法删除:' . "\n" . implode(',', $names));
        }
        $result = $this->table($role_table)->delete($id);
        return $this->returnMsg($result);
    }

}
